//
//  HRSearchFunChatFriendViewController.m
//  Hear
//
//  Created by mac on 2017/8/4.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRSearchFunChatFriendViewController.h"
#import "XHRadarView.h"
#import "HRSearchFunChatFriendViewModel.h"
#import "UIButton+SSEdgeInsets.h"
#import "HRCoverImageModel.h"
#import "HRDynamicViewController.h"

@interface HRSearchFunChatFriendViewController ()<XHRadarViewDataSource, XHRadarViewDelegate>

@property (nonatomic, strong) XHRadarView *radarView;
@property(nonatomic, strong)HRSearchFunChatFriendViewModel *viewModel;
@property (strong, nonatomic) NSTimer *timer;
@property(nonatomic, assign)BOOL isSearchSeccess;
@property(nonatomic, strong)UILabel *remendLabel;
@property(nonatomic, strong)UILabel *waitLabel;


@property(nonatomic, strong)UIView *showInfoView;
@property(nonatomic, strong)UIImageView *iconImageView;
@property(nonatomic, strong)UIButton *signButton;
@property(nonatomic, strong)UILabel *descLabel;
@property(nonatomic, strong)UIButton *continueButton;
@property(nonatomic, strong)UIButton *chatButton;
@property(nonatomic, strong)HRUpdataUserInfoModel *infoModel;
@property(nonatomic, strong)NSArray *remendArr;

@end

@implementation HRSearchFunChatFriendViewController
#pragma mark - Get and Set
- (HRSearchFunChatFriendViewModel *)viewModel{
    if (_viewModel == nil) {
        _viewModel = [[HRSearchFunChatFriendViewModel alloc] init];
    }
    return _viewModel;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupView];
    
    UIButton *leftButton = [UIButton buttonWithType:0];
    leftButton.frame = CGRectMake(20, 20+kStatusBarHeight, 20, 20);
    [leftButton setImage:[UIImage imageNamed:@"Back-Arrow"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:leftButton aboveSubview:self.view];

    
}



- (void)setupView{
    
    UIImageView *backImageView = [UIImageView new];
    backImageView.image = [UIImage imageNamed:@"FunChat_背景"];
    backImageView.userInteractionEnabled = YES;
    backImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:backImageView];
    
    WeakSelf

    [self addLoadContentView];
    
    
    self.showInfoView = [UIView new];
    [self.view addSubview:self.showInfoView];
    self.showInfoView.hidden = YES;
    
    
    self.iconImageView = [UIImageView new];
    [self.showInfoView addSubview:self.iconImageView];
    self.iconImageView.layer.cornerRadius = 40;
    self.iconImageView.clipsToBounds = YES;
    self.iconImageView.userInteractionEnabled = YES;
//    UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
//        if (weakSelf.showInfoView.isHidden)return;
//        HRDynamicViewController *dynaVC = [HRDynamicViewController new];
//        dynaVC.currentUserID = weakSelf.infoModel.LocalId;
//        [weakSelf.navigationController pushViewController:dynaVC animated:YES];
//    }];
//    [self.iconImageView addGestureRecognizer:iconTap];
    
    
    
    self.signButton = [UIButton buttonWithType:0];
//    [self.signButton setTitle:@"你不在 我也不在" forState:0];
    [self.signButton setTitleColor:[UIColor whiteColor] forState:0];
    self.signButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.showInfoView addSubview:self.signButton];
    
    
    NSArray *descArr = @[@"天南地北都能聊，文艺细胞特别发达的宅人一枚。",@"话虽然不是特别多但句句都能戳心窝的知心人士在此~",@"逗逼文艺，可攻可受，能屈能伸，可能是集万千性格于一身的万人迷吧~"];
    
    self.descLabel = [UILabel new];
    self.descLabel.text = descArr[arc4random() % descArr.count];
    self.descLabel.font = CustomUIFont(15);
    self.descLabel.textColor = [UIColor whiteColor];
    self.descLabel.numberOfLines = 0;
    [self.showInfoView  addSubview:self.descLabel];
    self.descLabel.textAlignment = 1;
    
    
    self.continueButton = [UIButton buttonWithType:0];
    [self.continueButton setTitle:@"换一个" forState:0];
    [self.continueButton setImage:[UIImage imageNamed:@"FunChat_换一个"] forState:0];
    [self.continueButton setTitleColor:[UIColor whiteColor] forState:0];
    self.continueButton.titleLabel.font = CustomUIFont(13);
    [self.continueButton addTarget:self action:@selector(continueButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.showInfoView addSubview:self.continueButton];
    
    
    
    self.chatButton = [UIButton buttonWithType:0];
    [self.chatButton setTitle:@"立即聊天" forState:0];
    [self.chatButton setImage:[UIImage imageNamed:@"FunChat_聊天"] forState:0];
    [self.chatButton setTitleColor:[UIColor whiteColor] forState:0];
    self.chatButton.titleLabel.font = CustomUIFont(13);
    [self.chatButton addTarget:self action:@selector(chatButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.showInfoView addSubview:self.chatButton];
    
    [backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
                         
    [self.showInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.showInfoView);
        make.top.equalTo(weakSelf.showInfoView).offset(100);
        make.size.mas_equalTo(CGSizeMake(80, 80));
    }];
    
    [self.signButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.iconImageView.mas_bottom).offset(10);
        make.left.right.equalTo(weakSelf.showInfoView);
        make.height.equalTo(@20);
    }];
    
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.signButton.mas_bottom).offset(20);
        make.left.equalTo(weakSelf.showInfoView).offset(10);
        make.right.equalTo(weakSelf.showInfoView).offset(-10);
        make.height.equalTo(@50);
    }];
    
    
    CGFloat continueButtonWidth = 73;
    CGFloat leftPading = (kFullWidth-continueButtonWidth*2)/4;
   [self.continueButton mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.equalTo(weakSelf.showInfoView).offset(leftPading);
       make.bottom.equalTo(weakSelf.showInfoView.mas_bottom).offset(-60);
       make.height.mas_equalTo(continueButtonWidth+15);
       make.width.mas_equalTo(continueButtonWidth);
   }];
    
    [self.chatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.showInfoView).offset(-leftPading);
        make.bottom.equalTo(weakSelf.continueButton.mas_bottom);
        make.size.equalTo(weakSelf.continueButton);
    }];
    [self.continueButton setImagePositionWithType:SSImagePositionTypeTop spacing:3];

    [self.chatButton setImagePositionWithType:SSImagePositionTypeTop spacing:3];

    
    
    [self  saveAppTopicUser]; //记入到匹配Loop中
}



#pragma mark 继续匹配
- (void)continueButtonClick{
    if (self.showInfoView.isHidden)return;
    self.remendLabel.hidden = NO;
    self.waitLabel.hidden = NO;
    self.isSearchSeccess = NO;
    self.radarView.hidden = NO;
    self.showInfoView.hidden = YES;
    [self.radarView scan];
    [self startTimer];
}

#pragma mark 聊天
- (void)chatButtonClick{
    if (self.showInfoView.isHidden)return;
    
    EaseMessageViewController *messgaeVC = [[EaseMessageViewController alloc] initWithConversationChatter:self.infoModel.LocalId conversationType:EMConversationTypeChat];
    messgaeVC.TopicTitle = self.TopicTitle;
    messgaeVC.TopicLocalId = self.TopicLocalId;
    messgaeVC.isFunChat = YES;
    messgaeVC.otherNickNameStr = self.infoModel.UserRemark.length>0?self.infoModel.UserRemark:self.infoModel.NickName;
    messgaeVC.otherIconStr = self.infoModel.UserPictureBackgroundColor;
    messgaeVC.otherIconName = self.infoModel.UserPictureName;
    messgaeVC.title = self.infoModel.UserRemark.length>0?self.infoModel.UserRemark:self.infoModel.NickName;
    [self.navigationController pushViewController:messgaeVC animated:YES];
}



- (void)saveAppTopicUser{
    
    WeakSelf
    [self.viewModel postSaveAppTopicUser:@{@"TopicLocalId":self.TopicLocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} isSeccess:^(BOOL isSeccess) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf startTimer];
        });
//        if (isSeccess){
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [weakSelf startTimer];
//            });
//        }else{
//            [weakSelf deleteAppTopicUser:YES];
//        }
    }];
}


- (void)increaseSearchTime{
    if (self.isSearchSeccess) return;
    self.remendLabel.text = self.remendArr[arc4random()%self.remendArr.count];

    [self getMatchUserInfo];
}

- (void)getMatchUserInfo{
    WeakSelf
    [self.viewModel getMatchUserInfo:@{@"TopicLocalId":self.TopicLocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} infoModel:^(HRUpdataUserInfoModel *infoModel) {
        if (infoModel){
            [weakSelf stopTimer];

            dispatch_async(dispatch_get_main_queue(), ^{
                [[EMCDDeviceManager sharedInstance] playVibration];
                weakSelf.infoModel = infoModel;
                weakSelf.isSearchSeccess = YES;
                [weakSelf.radarView stop];
                weakSelf.remendLabel.hidden = YES;
                weakSelf.waitLabel.hidden = YES;
                weakSelf.radarView.hidden = YES;
                [weakSelf showUserinfo];
            });
        }else{
            
        }
    }];
}


- (void)showUserinfo{
    self.showInfoView.hidden = NO;
    WeakSelf
    [self.signButton setTitle:self.infoModel.UserRemark.length>0?self.infoModel.UserRemark:self.infoModel.NickName forState:0];
    
//    self.iconImageView.image = [HRCoverImageModel OriginImage:[UIImage imageNamed:self.infoModel.UserPictureName] scaleToSize:CGSizeMake(80, 80)];
//    [HRCoverImageModel OriginImage:[UIImage imageNamed:self.infoModel.UserPictureName] scaleToSize:CGSizeMake(80, 80) callBackOriginImage:^(UIImage *originImage) {
//        weakSelf.iconImageView.image = originImage;
//    }];
    
//    self.iconImageView.backgroundColor = [UIColor colorWithHexString:self.infoModel.UserPictureBackgroundColor];
    
    [weakSelf.iconImageView.layer setImageURL:[NSURL URLWithString:self.infoModel.UserPictureName]];
    
}


#pragma mark 删除记录
- (void)deleteAppTopicUser:(BOOL)isSaveAppTopicUser{
    WeakSelf
    [self.viewModel deleteAppTopicUser:@{@"TopicLocalId":self.TopicLocalId,@"UserLocalId":USERID,@"CreateTime":[self getCurrentTime]} isSeccess:^(BOOL isSeccess) {
        if (isSeccess &&isSaveAppTopicUser){
            [weakSelf saveAppTopicUser];
        }
    }];
}


- (void)startTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5.0f target:self selector:@selector(increaseSearchTime) userInfo:nil repeats:YES];

}

- (void)stopTimer {
    if (_timer) {
        [_timer invalidate];
        self.timer = nil;
    }
}



- (void)addLoadContentView{
    
    CGFloat leftPaing = 60;
    CGFloat radarViewWidth = kFullWidth-leftPaing*2;
    
    XHRadarView *radarView = [[XHRadarView alloc] initWithFrame:CGRectMake(0, 0, kFullWidth,kFullHeight)];
//    radarView.frame = self.view.frame;
    radarView.dataSource = self;
    radarView.delegate = self;
    radarView.radius = radarViewWidth/2;
    radarView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:radarView];
    _radarView = radarView;
    radarView.indicatorStartColor = MainColor;
    

    
    self.waitLabel = [UILabel new];
    self.waitLabel.text = @"正在等待匹配";
    self.waitLabel.font = CustomUIFont(17);
    self.waitLabel.textColor = FirstTextColor;
    [self.view  addSubview:self.waitLabel];
    self.waitLabel.frame = CGRectMake(0, kFullHeight-80, kFullWidth, 20);
    self.waitLabel.textAlignment = 1;
    
    
    self.remendArr = @[@"不许说话骚里骚气的哦，不然我们会封杀你的！",@"富强民主文明和谐，做个好孩子呦！",@"不要着急，好的东西总是姗姗来迟。",@"清清嗓，活动活动手指，ta要来啦！"];
    
    self.remendLabel = [UILabel new];
    self.remendLabel.frame = CGRectMake(20, self.waitLabel.top-80, kFullWidth-40, 50);
    self.remendLabel.text = self.remendArr[arc4random()%self.remendArr.count];
    self.remendLabel.numberOfLines = 0;
    self.remendLabel.font = CustomUIFont(15);
    self.remendLabel.textColor = [UIColor whiteColor];
    [self.view  addSubview:self.remendLabel];
    self.remendLabel.textAlignment = 1;
    
    [self.radarView scan];

}





- (void)clickBack{
    [self deleteAppTopicUser:NO];

    [self.navigationController popViewControllerAnimated:YES];
}


- (NSString *)getCurrentTime
{
    
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    
    return [formatter stringFromDate:[NSDate date]];
}

-(void)dealloc{
    [self stopTimer];
    self.timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

#pragma mark 收到对方断开匹配通知
//- (void)DeleteAppTopicUserNotifi{
//    [self continueButtonClick];
//    [MBProgressHUD showMessage:@"对方拒绝了你的匹配" finishBlock:nil];
//}

#pragma mark 收到对方匹配的人的信息
//-(void)getMatchUserInfoNotifi:(NSNotification *)notifi{
//    
//    [self stopTimer];
//
//    
//    NSDictionary *userDict = notifi.object;
//    
//    [[EMCDDeviceManager sharedInstance] playVibration];
//    self.infoModel = [HRUpdataUserInfoModel new];
//    self.infoModel.NickName = userDict[@"nickname"];
//    self.infoModel.UserPictureName = userDict[@"UserPictureName"];
//    self.infoModel.UserPictureBackgroundColor = userDict[@"UserPictureBackgroundColor"];
//    self.infoModel.LocalId = userDict[@"userId"];
//    self.isSearchSeccess = YES;
//    [self.radarView stop];
//    self.remendLabel.hidden = YES;
//    self.waitLabel.hidden = YES;
//    self.radarView.hidden = YES;
//    [self showUserinfo];
//    
//    DDLog(@"");
//}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];

//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DeleteAppTopicUserNotifi) name:@"DeleteAppTopicUserNotifi" object:nil];
//    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMatchUserInfoNotifi:) name:@"getMatchUserInfoNotifi" object:nil];

}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];

}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self deleteAppTopicUser:NO];
    [self stopTimer];

//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
